package com.travel.worker;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.travel.modules.alipay.entity.OrderForm;
import com.travel.modules.alipay.service.OrderFormService;
import com.travel.modules.asset.entity.Advertise;
import com.travel.modules.asset.service.AdvertiseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 订单过期检查
 */
@Slf4j
@Component
@EnableScheduling
public class Jobs {
    @Resource
    private OrderFormService orderFormService;

    @Resource
    private AdvertiseService advertiseService;

    /**
     * 订单过期检查
     */
    @Scheduled(cron = "0/1 * * * * ? ")
    void orderExpireChecker() {
        List<OrderForm> orders = orderFormService.list(new QueryWrapper<OrderForm>().eq("status", 0));
        boolean isUpdate = false;

        for (OrderForm order : orders) {
            if (order.getExpireTime() == null) {
                continue;
            }
            if (new Date().after(order.getExpireTime())) {
                log.warn("订单过期 : " + order.getOrderId());
                order.setStatus(-2);
                isUpdate = true;
            }
        }

        if (isUpdate) {
            orderFormService.updateBatchById(orders);
        }
    }

    /**
     * 广告过期检查
     */
    @Scheduled(cron = "0/1 * * * * ? ")
    void advertiseExpireChecker() {
        List<Advertise> ads = advertiseService.list(new QueryWrapper<Advertise>().eq("status", 1));
        boolean isDel = false;

        List<Integer> toDel = new ArrayList<>();
        for (Advertise ad : ads) {
            if (ad.getExpireTime() == null) {
                continue;
            }
            if (new Date().after(ad.getExpireTime())) {
                log.warn("广告过期 ： " + ad.getAdId());
                toDel.add(ad.getId());
                isDel = true;
            }
        }

        if (isDel) {
            advertiseService.removeByIds(toDel);
        }
    }
}
